#include "../include/RssReader.hpp"

void RssReader::parseRss(const string &fileName)
{
	XMLDocument doc;
	doc.LoadFile(fileName.c_str());
	if (doc.ErrorID())
	{
		return;
	}
	// 获取root节点的指针
	XMLElement *root = doc.FirstChildElement("rss");
	// 获取第一个<item>元素节点的指针
	XMLElement *itemElem =
		root->FirstChildElement("channel")->FirstChildElement("item");

	std::regex re("<.*?>");
	do
	{
		XMLElement *titleElem = itemElem->FirstChildElement("title");
		string title;
		if (titleElem == nullptr)
		{
			title = "";
		}
		else
		{
			const char *_title = titleElem->GetText();
			if (_title == NULL)
			{
				title = "";
			}
			else
			{
				title = _title;
			}
		}

		XMLElement *linkElem = itemElem->FirstChildElement("link");
		string link;
		if (linkElem == nullptr)
		{
			link = "";
		}
		else
		{
			const char *_link = linkElem->GetText();
			if (_link == NULL)
			{
				link = "";
			}
			else
			{
				link = _link;
			}
		}

		XMLElement *descriptElem =
			itemElem->FirstChildElement("description");
		string origin1;
		if (descriptElem == nullptr)
		{
			origin1 = "";
		}
		else
		{
			const char *descript = descriptElem->GetText();
			if (descript == NULL)
			{
				origin1 = "";
			}
			else
			{
				origin1 = descript;
			}
		}

		XMLElement *contentElem =
			itemElem->FirstChildElement("content:encoded");
		string origin2;
		if (contentElem == nullptr)
		{
			origin2 = "";
		}
		else
		{
			const char *content = contentElem->GetText();
			if (content == NULL)
			{
				origin2 = "";
			}
			else
			{
				origin2 = content;
			}
		}

		RssItem item;
		item.title = title;
		item.link = link;
		item.description = std::regex_replace(origin1, re, "");
		item.content = std::regex_replace(origin2, re, "");

		_rss.push_back(item);
	} while ((itemElem = itemElem->NextSiblingElement("item")) != nullptr);
	// 寻找第一个标签为<item>的同级节点
}

vector<RssItem> RssReader::getVecRss()
{
	return _rss;
}